sudo nano /usr/local/bin/website_monitor.sh



#!/bin/bash

# 监控配置
LOG_FILE="/var/log/website_monitor.log"
PHP_API_URL="http://your-website.com/monitor_api.php"  # 替换为您的PHP接口地址
API_KEY="your_secret_key_here"  # 用于身份验证的密钥

# 推送数据到PHP接口
push_to_php() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local monitor_type="$1"
    local status="$2"
    local details="$3"
    local severity="$4"
    
    # 构建JSON数据
    local json_data=$(cat <<EOF
{
    "timestamp": "$timestamp",
    "type": "$monitor_type",
    "status": "$status",
    "details": "$details",
    "severity": "$severity",
    "api_key": "$API_KEY"
}
EOF
)
    
    # 发送HTTP POST请求
    local response=$(curl -s -w "%{http_code}" -X POST \
        -H "Content-Type: application/json" \
        -d "$json_data" \
        "$PHP_API_URL")
    
    local http_code=${response: -3}
    local response_body=${response%???}
    
    if [ "$http_code" = "200" ]; then
        echo "数据推送成功: $monitor_type - $status"
    else
        echo "数据推送失败 (HTTP $http_code): $response_body"
        # 失败时仍然记录到本地日志
        echo "$timestamp - [推送失败] $monitor_type: $status - $details" >> "$LOG_FILE"
    fi
}

# 修改监控函数，添加推送调用
monitor_mysql() {
    # 原有的MySQL监控代码...
    THREADS_CONNECTED=$(mysql -e "SHOW STATUS LIKE 'Threads_connected'" -s -N | awk '{print $2}')
    MAX_CONNECTIONS=$(mysql -e "SHOW VARIABLES LIKE 'max_connections'" -s -N | awk '{print $2}')
    CONNECTION_USAGE=$(( THREADS_CONNECTED * 100 / MAX_CONNECTIONS ))
    
    local status="normal"
    local severity="info"
    
    if [ $CONNECTION_USAGE -gt 80 ]; then
        status="warning"
        severity="warning"
    elif [ $CONNECTION_USAGE -gt 90 ]; then
        status="critical"
        severity="error"
    fi
    
    local details="连接数: $THREADS_CONNECTED/$MAX_CONNECTIONS (${CONNECTION_USAGE}%)"
    
    # 推送到PHP接口
    push_to_php "mysql_connections" "$status" "$details" "$severity"
    
    echo "MySQL - $details"
}

monitor_php_website() {
    local url="http://your-website.com"
    local http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 10 "$url")
    local response_time=$(curl -s -o /dev/null -w "%{time_total}" --connect-timeout 10 "$url")
    
    local status="normal"
    local severity="info"
    local details="HTTP状态: $http_code, 响应时间: ${response_time}s"
    
    if [ "$http_code" != "200" ]; then
        status="critical"
        severity="error"
    elif [ "$(echo "$response_time > 3" | bc)" -eq 1 ]; then
        status="warning"
        severity="warning"
    fi
    
    # 推送到PHP接口
    push_to_php "website_health" "$status" "$details" "$severity"
    
    echo "网页监控 - $details"
}
